package classes;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author Bel
 */
public class Xml {

    private String fileName;
    private Document doc;

    public Xml(String fileName) {
        this.fileName = fileName;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public Document carregaXml() {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = (Document) db.parse(new File(fileName));

        } catch (SAXException | IOException | ParserConfigurationException ex) {
            Logger.getLogger(Xml.class.getName()).log(Level.SEVERE, null, ex);
        }
        return doc;
    }

    public Element criaNovoElemento(String elemento, String[] atributos, Object[] valores) {
        Element child = doc.createElement(elemento);
        for (int i = 0; i < valores.length; i++) {
            child.setAttribute(atributos[i].toString(), valores[i].toString());
        }
        return child;
    }

    public void grava() {
        try {
            TransformerFactory tranFactory = TransformerFactory.newInstance();
            Transformer aTransformer = tranFactory.newTransformer();
            Source src = new DOMSource(doc);
            Result dest = new StreamResult(new File(fileName));
            aTransformer.transform(src, dest);
        } catch (TransformerException ex) {
            Logger.getLogger(Xml.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void excluir(String descricao) {
        try {
            carregaXml();
            Element raiz = doc.getDocumentElement();

            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile("//pergunta[@descricao='" + descricao + "']");
            Object result = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList nl = (NodeList) result;
            raiz.removeChild(nl.item(0));
            grava();
        } catch (XPathExpressionException ex) {
            System.out.println(ex.getCause());
        }

    }
}
